package org.theSeed.handler;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.theSeed.pojo.dto.UserInfo;
import org.theSeed.rbacBaseCommon.pojo.constant.RbacConstant;
import org.theSeed.redisIntegration.utils.RedisUtil;
import org.theSeed.utils.LoginHelper;

import java.io.Serializable;

/**
 * 颗粒鉴权实际执行器
 */
@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        String permissionCode = (String) permission;
        UserInfo userInfo = LoginHelper.getUserInfo();
        if (ObjectUtil.isNotNull(userInfo)){
            String roleCode = userInfo.getSelectRoleCode();
            if (ObjectUtil.isNotEmpty(roleCode)){
                Object value = RedisUtil.getRedissonClient()
                        .getMap(RbacConstant.API_PERMISSION_KEY_PREFIX + roleCode)
                        .get(permissionCode);
                if (ObjectUtil.isNotNull(value))
                    return true;
            }
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}